//
//  iTools.m
//  ReaderFramework
//
//  Created by 王越 on 15/1/30.
//  Copyright (c) 2015年 wangyue. All rights reserved.
//

#import "iTools.h"
#import <CommonCrypto/CommonDigest.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#import "OpenUDID.h"
#define NSUserKeySessionid @"sessionid"
#define NSUserCookie  @"userCookie"
@implementation iTools


///////////////////////////////////////////////
///////////////日志相关//////////////////////
//////////////////////////////////////////////

/**
 *  打印错误日志
 *
 *  @param exception <#exception description#>
 */
+(void)logException:(NSException*)exception
{
    NSLog(@"name=%@;reason=%@",exception.name,exception.reason);
}

/**
 *  打印日志
 *
 */
+(void)log:(NSString*)log
{
    NSLog(@"wd=%@",log);
}


///////////////////////////////////////////////
///////////////系统参数相关//////////////////////
//////////////////////////////////////////////

/**
 * 获取软件版本号
 *  @return 版本号
 */
+ (NSString *)getVersion
{    
    NSDictionary * info = [[NSBundle mainBundle] infoDictionary];
    
    NSString *platform = [info objectForKey:@"CHCPlatform"];
    NSString *version = [info objectForKey:@"CFBundleShortVersionString"];
    NSString *channel = [info objectForKey:@"CBCChannel"];
    NSString *channelId = [info objectForKey:@"CBCChannelId"];
    
    return [NSString stringWithFormat:@"%@.%@.%@.%@",platform,version,channel,channelId];
}

/**
 * 获取软件版本号
 *  @return 版本号
 */
+ (NSString *)getVersion2
{
    NSDictionary * info = [[NSBundle mainBundle] infoDictionary];
    
    NSString *version = [info objectForKey:@"CFBundleShortVersionString"];
    NSString *channel = [info objectForKey:@"CBCChannel"];
    NSString *channelId = [info objectForKey:@"CBCChannelId"];
    
    return [NSString stringWithFormat:@"%@.%@.%@",version,channel,channelId];
}

/**
 *  获取域名
 *
 *  @return 域名
 */
+(NSString*) ServerHost {
    NSDictionary * info = [[NSBundle mainBundle] infoDictionary];
    return [info objectForKey:@"CbchotUrl"];
}

/**获取会员页面*/
+ (NSString *)vipUrl{
    NSString *url = [NSString stringWithFormat:@"%@/ios/pay/vip", [self ServerHost]];
    return  url;
}

/**阅读搜索页面*/
+ (NSString *)readingSearchUrl{
    NSString *url = [NSString stringWithFormat:@"%@/android/book/search", [self ServerHost]];
    return  url;
}
/**
 *  url绝对地址
 *
 *  @param url 相对地址
 *
 *  @return 绝对地址
 */
+ (NSString *)getHttpUrl:(NSString *)url
{
    if(![url hasPrefix:@"http://"]){
        url = [NSString stringWithFormat:@"%@%@", [self ServerHost], url];
    }
    return url;
}

/**
 *  获取系统版本号
 *
 *  @return <#return value description#>
 */
+ (float)getSystemVersion
{
    return [[UIDevice currentDevice] systemVersion].floatValue;
}

/**
 *  获取手机型号
 *
 *  @return <#return value description#>
 */
+ (NSString*)getPhoneType
{
    return [[UIDevice currentDevice] model];
}

/**
 * 获取屏幕像素高度
 */
+ (int)getScreenWidth
{
    CGRect rect=[[UIScreen mainScreen] bounds];
    CGFloat scale = [[UIScreen mainScreen] scale];
    int width = rect.size.width*scale;
    return width;
}

/**
 * 获取屏幕像素高度
 */
+ (int)getScreenHeight
{
    CGRect rect=[[UIScreen mainScreen] bounds];
    CGFloat scale = [[UIScreen mainScreen] scale];
    int height = rect.size.height*scale;
    return height;
}

/**
 * 获取屏幕大小
 */
+ (NSString *)getScreenSize
{
    CGRect rect=[[UIScreen mainScreen] bounds];
    CGFloat scale = [[UIScreen mainScreen] scale];
    int width = rect.size.width*scale;
    int height = rect.size.height*scale;
    NSString *screenSize = [NSString stringWithFormat:@"%d*%d",width,height];
    return screenSize;
}

/**获取手机唯一标识*/
+(NSString *)getUDID{
      return [OpenUDID value];
}
/**
 *  获取ip地址
 *
 *  @return <#return value description#>
 */
+ (NSString *)getIPAddress
{
    NSString *address = nil;
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = getifaddrs(&interfaces);
    if (success == 0) {
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return address;
}

/**
 *  打开系统浏览器
 *
 *  @param url <#url description#>
 */
+ (void)openSystemBrowser:(NSString *)url
{
    NSURL *nsUrl = [NSURL URLWithString:url];
    [[UIApplication sharedApplication] openURL:nsUrl];
}


///////////////////////////////////////////////
///////////////时间相关/////////////////////////
//////////////////////////////////////////////

/**
 *  获取时间戳
 *
 *  @return <#return value description#>
 */
+ (NSTimeInterval)getCurrentTime
{
    NSDate *date = [NSDate date];
    NSTimeInterval time = [date timeIntervalSince1970];
    return time;
}

/**
 *  获取时间戳
 *
 *  @return <#return value description#>
 */
+ (NSString*)getCurrentTimeMillis
{
    NSDate *date = [NSDate date];
    NSTimeInterval time = [date timeIntervalSince1970]*1000;//毫秒数要乘以1000
    double i = time;
    NSString *timeIntervalStr = [NSString stringWithFormat:@"%.f", i];
    return timeIntervalStr;
}

/**
 *  获取格式化时间
 *
 *  @param l 目标时间
 *
 *  @return <#return value description#>
 */
+(NSString*)getDateFormat:(NSString*)time
{
    if(time == nil || time.length == 0){
        return @"";
    }
    //发送时间
    double timeDou = [time doubleValue];
    if(timeDou == 0){
        return @"";
    }
    
    NSString *timeStr = @"";
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeDou/1000];
    NSDateComponents *dd = [cal components:unitFlags fromDate:date];
    NSInteger year = [dd year];
    NSInteger month = [dd month];
    NSInteger day = [dd day];
    //    NSInteger hour = [dd hour];
    //    NSInteger minute = [dd minute];
    //    NSInteger second = [dd second];
    
    //获取当前时间
    NSDateComponents *currentDateC = [cal components:unitFlags fromDate:[iTools getCurrentDateTime]];
    NSInteger currentYear = [currentDateC year];
    NSInteger currentMonth = [currentDateC month];
    NSInteger currentDay = [currentDateC day];
    //    NSInteger currentHour = [currentDateC hour];
    //    NSInteger currentMinute = [currentDateC minute];
    //    NSInteger currentSecond = [currentDateC second];
    
    if(year == currentYear && month == currentMonth && ((currentDay - day) <= 1)){
        if((currentDay - day) == 0){//今天
            timeStr = [iTools getFormatDate:date FormatTime:@"HH:mm"];
        }else if((currentDay - day) == 1){//昨天
            timeStr = [@"昨天 " stringByAppendingString:[iTools getFormatDate:date FormatTime:@"HH:mm"]];
        }
    }else{
        timeStr = [iTools getFormatDate:date FormatTime:@"yyyy-MM-dd HH:mm"];
    }
    return timeStr;
}

/**
 *  获取当前时间
 *
 *  @return <#return value description#>
 */
+(NSDate*)getCurrentDateTime
{
    return [NSDate date];
}

/**
 *  获取当前格式化时间
 *
 *  @return <#return value description#>
 */
+(NSString*)getCurrentDateTimeStr
{
    return [self getFormatDateTime:[NSDate date]];
}

/**
 *  获取指定格式化时间
 *
 *  @param time <#time description#>
 *
 *  @return <#return value description#>
 */
+(NSString*)getFormatDateTime:(NSDate*)time
{
    return [self getFormatDate:time FormatTime:@"yyyy-MM-dd HH:mm:ss"];
}

/**
 *  获取指定时间，指定格式的时间
 *
 *  @param time   时间
 *  @param format 格式
 *
 *  @return <#return value description#>
 */
+(NSString*)getFormatDate:(NSDate*)time FormatTime:(NSString*)format
{
    NSDateFormatter* formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    [formatter setLocale:[NSLocale currentLocale]];
    return [formatter stringFromDate:time];
}

/**
 *  时间转换，string to date
 *
 *  @param dateString <#dateString description#>
 *
 *  @return <#return value description#>
 */
+ (NSDate *)getDateFromString:(NSString *)dateString
{
    return [self getDateFromString:dateString FormatTime:@"yyyy-MM-dd HH:mm:ss"];
}

/**
 *  时间转换，string to date
 *
 *  @param dateString <#dateString description#>
 *
 *  @return <#return value description#>
 */
+ (NSDate *)getDateFromString:(NSString *)dateString FormatTime:(NSString*)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: format];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}


///////////////////////////////////////////////
///////////////网络相关/////////////////////////
//////////////////////////////////////////////

/**
 *  获取网络是否可用
 *
 *  @return <#return value description#>
 */
+ (BOOL)networkConnected{
    BOOL result = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable ||
                   [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
    return result;
}

/**
 *  获取wifi网络是否可用
 *
 *  @return <#return value description#>
 */
+ (BOOL)networkWifiConnected{
    BOOL result = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable;
    return result;
}

/**
 * 获取当前网络
 */
+(NetworkStatus)getCurrentNetwork
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    return [reach currentReachabilityStatus];
}


///////////////////////////////////////////////
///////////////配置文件相关//////////////////////
//////////////////////////////////////////////

/**
 *  获取UserDefault值
 *
 *  @param key <#key description#>
 *
 *  @return <#return value description#>
 */
+ (id)getUserDefaultValue:(NSString *)key
{
    NSUserDefaults *_defaults = [NSUserDefaults standardUserDefaults];
    if ([_defaults valueForKey:key]) {
        return [_defaults valueForKey:key];
    }
    return nil;
}

/**
 *  设置UserDefault值
 *
 *  @param value <#value description#>
 *  @param key   <#key description#>
 */
+ (void)setUserDefaultValue:(id)value forKey:(NSString *)key
{
    if (value && key) {
        NSUserDefaults *_defaults = [NSUserDefaults standardUserDefaults];
        [_defaults setValue:value forKey:key];
        [_defaults synchronize];
    }
}

/**
 *  设置用户Cookie值
 *
 *  @param cookie <#cookie description#>
 */
+(void)saveCookieValue:(NSHTTPCookie *)cookie{
    
    NSLog(@"cookie===%@",cookie);
    
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];
    [cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];
    [cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];
    [cookieProperties setObject:[NSNumber numberWithInt:(int)cookie.version] forKey:NSHTTPCookieVersion];
    
    [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
    
    [[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:NSUserCookie];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


///////////////////////////////////////////////
///////////////文件操作相关//////////////////////
//////////////////////////////////////////////

/**
 *  创建文件夹
 */
+(BOOL)createDirectory:(NSString*)path
{
    NSMutableArray *subArr = [NSMutableArray arrayWithArray:[path componentsSeparatedByString:@"/"]];
    //先保证创建目录是document路径下的二级目录
    if(subArr.count > 1){
        //移除首个空行
        [subArr removeObjectAtIndex:0];
        //移除文件名
        [subArr removeLastObject];
        //开始创建文件夹
        NSString *componentPath = @"";
        for(int i=0;i<subArr.count;i++){
            componentPath = [componentPath stringByAppendingPathComponent:subArr[i]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL isDir = NO;
            BOOL isDirExist = [fileManager fileExistsAtPath:componentPath isDirectory:&isDir];
            if(!(isDirExist && isDir)){
                BOOL bCreateDir = [fileManager createDirectoryAtPath:componentPath withIntermediateDirectories:YES attributes:nil error:nil];
                if(!bCreateDir){
                    return NO;
                }
            }
        }
    }
    return YES;
}

/**
 *  判断文件是否存在,YES存在，NO不存在
 */
+(BOOL)isFileExists:(NSString*)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        return YES;
    }
    return NO;
}

/**
 *  创建文件
 *
 *  @param tempImage <#tempImage description#>
 *  @param imageName <#imageName description#>
 *
 *  @return <#return value description#>
 */
+(BOOL)createFile:(NSData *)data WithName:(NSString *)path
{
    //创建文件夹
    [self createDirectory:path];
    //写文件
    return [data writeToFile:path atomically:NO];
}

/**
 *  删除文件
 *
 *  @param path <#path description#>
 */
+(void)deleteFile:(NSString*)path
{
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

/**
 *  将byte变为M
 *
 *  @param size <#size description#>
 *
 *  @return <#return value description#>
 */
+(NSString*)formatByteToM:(int)size
{
    int a = size/1024;
    int b = a/1024;
    int c= a%1024;
    return [NSString stringWithFormat:@"%d.%dM",b,c];
}


/**
 *  获取Caches文件夹
 *
 *  @return 路径
 */
+(NSString *)getCachesDirectory
{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [array objectAtIndex:0];
}

/**
 *  获取Document文件夹
 *
 *  @return <#return value description#>
 */
+(NSString *)getDocumentDirectory
{
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [arr objectAtIndex:0];
}

/**
 *  获取缓存文件地址
 *
 *  @return <#return value description#>
 */
+(NSString *)getCacheFileDirectory:(NSString*)fileName
{
    NSString* path = [[self getDocumentDirectory] stringByAppendingFormat:@"/cover/%@",fileName];
    return path;
}


///////////////////////////////////////////////
///////////////视图相关/////////////////////////
//////////////////////////////////////////////

/**
 *  获取窗口
 *
 *  @return <#return value description#>
 */
+ (UIWindow *)getWindow
{
    return [(AppDelegate*)[UIApplication sharedApplication].delegate window];
}

/**
 *  加入窗口
 *
 *  @param view <#view description#>
 */
+(void)addWindos:(UIView *) view{
    AppDelegate * delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.window addSubview:view];
    [delegate.window bringSubviewToFront:view];
}


/**
 *  显示状态栏
 *
 *  @param aStyle <#aStyle description#>
 */
+(void)showHideStatusBar
{
    if ([UIApplication sharedApplication].statusBarHidden) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    }else{
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    }
}

 
//16进制颜色转换成UIColor
+ (UIColor *)getHexColor:(NSString *)hexColor
{
    NSString *cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

+(CGSize)customTextSize:(UIFont *)font text:(NSString *)inputString size:(CGSize)inputSize{
    CGSize result;
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
    //NSStringDrawingUsesLineFragmentOrigin
     CGRect rect1=[inputString boundingRectWithSize:inputSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
    result=rect1.size;
    return result;
}

/**
 * 显示警告框
 */
+(void)showAlert:(NSString*)title Message:(NSString *)message BtnStr:(NSString*)btnStr{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:btnStr otherButtonTitles:nil, nil];
    [alert show];
}

//得到当前屏幕的视图控制器
+(id)getCurrentScreenController
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    return result;
}


///////////////////////////////////////////////
///////////////图片相关//////////////////////
//////////////////////////////////////////////

/**
 *  图片旋转
 *
 *  @param image       <#image description#>
 *  @param orientation <#orientation description#>
 *
 *  @return <#return value description#>
 */
+(UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    long double rotate = 0.0;
    CGRect rect;
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    //得到新绘制的图片对象
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newPic;
}

/**
 *  图片翻转正
 *
 *  @param aImage <#aImage description#>
 *
 *  @return <#return value description#>
 */
+ (UIImage *)imageOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

/**
 *  图片压缩
 *
 *  @param originImage <#originImage description#>
 *
 *  @return <#return value description#>
 */
+(NSData*)imageCompress:(UIImage*)originImage
{
    //压缩图片尺寸
    CGFloat w = originImage.size.width;
    CGFloat h = originImage.size.height;
    
    CGFloat targetWH = 2000;
    CGFloat scale = 1.0;
    
    if(w > h){//宽图
        if(h>targetWH){//当高度大于屏幕高度，缩小尺寸
            scale = h/targetWH;
        }
    }else if(w<h){//瘦图
        if(w > targetWH){//当宽度大于屏幕宽度，缩小尺寸
            scale = w/targetWH;
        }
    }
    
    UIImage* newImage;
    if(scale > 1){
        CGFloat newW = w/scale;
        CGFloat newH = h/scale;
        // Create a graphics image context
        UIGraphicsBeginImageContext(CGSizeMake(newW, newH));
        // new size
        [originImage drawInRect:CGRectMake(0,0,newW,newH)];
        // Get the new image from the context
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        // End the context
        UIGraphicsEndImageContext();
    }else{
        newImage = originImage;
    }

    //压缩图片质量
    NSData* data = UIImageJPEGRepresentation(newImage,1);
    CGFloat targetSize = 100*1024;
    if(data.length > targetSize){//假如大于100k
        CGFloat scaleSize = targetSize/data.length;
        data = UIImageJPEGRepresentation(newImage,scaleSize);
    }
    
    return data;
}

/**
 *  将UIView转换为UIImage
 *
 *  @param view <#view description#>
 *
 *  @return <#return value description#>
 */
+(UIImage*)convertViewToImage:(UIView*)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


///////////////////////////////////////////////
///////////////其它相关//////////////////////
//////////////////////////////////////////////

/**
 *  拷贝到粘贴板
 */
+(void)copyToPasteboard:(NSString*)msg
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = msg;
}

/**
 *  验证字符串是不是为数字,字母
 *
 *  @param title
 *
 *  @return
 */
+(BOOL)evaluateStringAlpbetAndNumber:(NSString *)title{
    BOOL isDecide = TRUE;
    NSString *regex = @"[a-zA-Z0-9]+";
    //SELF是指字符串本身 MATCHES正则表达式
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if(![pred evaluateWithObject:title]){
        return FALSE;
    }
    return isDecide;
}

/**
 判断是不是有效的手机号码

 @param mobile <#mobile description#>

 @return <#return value description#>
 */
+ (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"手机号长度只能是11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确的电话号码";
        }
    }
    return nil;
}

/**
 判断传进来的字符串是否为null

 @param inputStr <#inputStr description#>

 @return <#return value description#>
 */
+(BOOL)decideIsEmpty:(NSString *)inputStr{
    BOOL decide=FALSE;
    if([inputStr isEqual:[NSNull null]] || inputStr==nil || [inputStr isEqualToString:@"null"] || [inputStr isEqualToString:@""]){
        decide=TRUE;
    }
    return decide;
}

/**
 *  获取随机数字符串
 *
 *  @return <#return value description#>
 */
+(NSString*)getRandom
{
    int x = arc4random() % 100;
    NSString* random = [NSString stringWithFormat:@"%@%d",[self getCurrentTimeMillis],x];
    return random;
}

/**
 获得一个随机颜色

 @return <#return value description#>
 */
+(UIColor*)getRandomColor
{
    return [UIColor colorWithRed:arc4random()%256/255.0f green:arc4random()%256/255.0f blue:arc4random()%256/255.0f alpha:1];
}

/**
 *  字符串转MD5码
 *
 *  @param str <#str description#>
 *
 *  @return <#return value description#>
 */
+ (NSString *)md5Hash:(NSString *)key
{
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *md5Result = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return md5Result;
}


/**
 切分字符串

 @param path      <#path description#>
 @param splitChar <#splitChar description#>

 @return <#return value description#>
 */
+(NSMutableArray*)splitString:(NSString*)path SplitChar:(NSString*)splitChar
{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:5];
    @try {
        
        while(true){
            NSRange index0 = [path rangeOfString:splitChar];
            if(index0.length > 0){
                NSString* str = [path substringToIndex:index0.location];
                path = [path substringFromIndex:(index0.location+index0.length)];
                [array addObject:str];
            }else{
                [array addObject:path];
                break;
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception reason]);
    }
    return array;
}



@end
